package com.laker.autotest.utils;

import cn.hutool.core.io.FileUtil;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.impl.driver.Driver;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static java.util.Arrays.asList;

@Slf4j
public class PlaywrightUtil {

    private PlaywrightUtil() {
        // 私有构造
    }

    public static Playwright initPlaywright() {
        Playwright.CreateOptions createOptions = new Playwright.CreateOptions();
        Map<String, String> env = new HashMap<>();
        env.put("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "1");
        env.put("PLAYWRIGHT_DOWNLOAD_HOST", "https://registry.npmmirror.com/-/binary/playwright");
        createOptions.setEnv(env);
        return Playwright.create(createOptions);
    }

    @SneakyThrows
    public static void command(String[] args) {
        Map<String, String> env = new HashMap<>();
        env.put("PLAYWRIGHT_DOWNLOAD_HOST", "https://registry.npmmirror.com/-/binary/playwright");
        Driver driver = Driver.ensureDriverInstalled(env, false);
        ProcessBuilder pb = driver.createProcessBuilder();
        pb.command().addAll(asList(args));
        String version = Playwright.class.getPackage().getImplementationVersion();
        if (version != null) {
            pb.environment().put("PW_CLI_DISPLAY_VERSION", version);
        }
        pb.inheritIO();
        Process process = pb.start();
        System.exit(process.waitFor());
    }

    /**
     * @param browserName 浏览器名称 eg: chromium, firefox, webkit
     */
    @SneakyThrows
    public static void installBrowser(String browserName) {
        String version = Playwright.class.getPackage().getImplementationVersion();
        String path = "/opt/easy";
        String fileName = version + "-" + browserName + ".easy";
        if (FileUtil.exist(path + "/" + fileName)) {
            log.warn(">>>>>>>>>>>>>>>> {} Browser Already Installed. Skip.", browserName);
            return;
        }

        Map<String, String> env = new HashMap<>();
        env.put("PLAYWRIGHT_DOWNLOAD_HOST", "https://registry.npmmirror.com/-/binary/playwright");
        Driver driver = Driver.ensureDriverInstalled(env, false);
        ProcessBuilder pb = driver.createProcessBuilder();
        pb.command().addAll(asList("install", "--with-deps", browserName));
        if (version != null) {
            pb.environment().put("PW_CLI_DISPLAY_VERSION", version);
        }
        pb.inheritIO();
        Process p = pb.start();
        boolean result = p.waitFor(10L, TimeUnit.MINUTES);
        if (!result) {
            p.destroy();
            throw new RuntimeException("Timed out waiting for browsers to install");
        } else if (p.exitValue() != 0) {
            throw new RuntimeException("Failed to install browsers, exit code: " + p.exitValue());
        }
        FileUtil.mkdir(path);
        boolean success = FileUtil.newFile(path + "/" + fileName).createNewFile();
        log.info(">>>>>>>>>>>>>>>> {} Browser installation completed, result:{}", browserName, success);
    }

}
